package com.tdam2011.grupo02.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.domain.ContactosInfo;

public class ContactosInfoAdapter extends BaseAdapter {
	private ArrayList<ContactosInfo> contactosInfos;
	private LayoutInflater inflater;

	public ContactosInfoAdapter(Context context) {
		
		contactosInfos = new ArrayList<ContactosInfo>();
		inflater = LayoutInflater.from(context);
	}

	public void addContactosInfo(ContactosInfo info) {
		if (info != null) {
			contactosInfos.add(info);
		}
	}

	@Override
	public int getCount() {
		return contactosInfos.size();
	}

	@Override
	public Object getItem(int position) {
		return contactosInfos.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	class Holder {
		private ImageView imagen;
		private TextView nombre;
		private TextView tipo;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		Holder holder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item_contacto, null);
			holder = new Holder();
			holder.imagen = (ImageView) convertView
					.findViewById(R.id.imgvContactoImg);
			holder.nombre = (TextView) convertView
					.findViewById(R.id.txtvContactoNombre);
			holder.tipo = (TextView) convertView
					.findViewById(R.id.txtvContactoTipo);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
		ContactosInfo info = (ContactosInfo) getItem(position);
		
		InputStream input;
		Bitmap bm=null;
		try {
			if(info.getImagen()!=null){
				input = inflater.getContext().getContentResolver().openInputStream(info.getImagen());
				bm = BitmapFactory.decodeStream(input);
				input.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		holder.imagen.setImageBitmap(bm);
		holder.nombre.setText(info.getNombre());
		holder.tipo.setText(info.getTipo());

		return convertView;
	}

}
